package com.loiane.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.loiane.model.Account;
import com.loiane.service.AccountService;

@Controller
public class AccountController {

	private AccountService accountService;

	@RequestMapping(value = "/account/view.action")
	public @ResponseBody
	Map<String, ? extends Object> view() throws Exception {

		try {

			List<Account> accounts = accountService.getAccountsList();
			return getMap(accounts);

		} catch (Exception e) {

			return getModelMapError("Error retrieving Contacts from database.");
		}
	}

	@RequestMapping(value = "/account/create.action")
	public @ResponseBody
	Map<String, ? extends Object> create(@RequestParam Object data)
			throws Exception {

		try {

			List<Account> accounts = accountService.create(data);

			return getMap(accounts);

		} catch (Exception e) {

			return getModelMapError("Error trying to create contact.");
		}
	}

	@RequestMapping(value = "/account/update.action")
	public @ResponseBody
	Map<String, ? extends Object> update(@RequestParam Object data)
			throws Exception {
		try {
			List<Account> accounts = accountService.update(data);
			return getMap(accounts);
		} catch (Exception e) {
			return getModelMapError("Error trying to update Account.");
		}
	}

	@RequestMapping(value = "/account/delete.action")
	public @ResponseBody
	Map<String, ? extends Object> delete(@RequestParam Object data)
			throws Exception {
		try {
			accountService.delete(data);
			Map<String, Object> modeMap = new HashMap<String, Object>(4);
			modeMap.put("Success", true);
			return modeMap;
		} catch (Exception e) {
			return getModelMapError("Error trying to delete account.");
		}
	}

	private Map<String, Object> getMap(List<Account> accounts) {

		Map<String, Object> modelMap = new HashMap<String, Object>(3);
		modelMap.put("total", accounts.size());
		modelMap.put("data", accounts);
		modelMap.put("success", true);

		return modelMap;
	}

	private Map<String, Object> getModelMapError(String msg) {

		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		modelMap.put("message", msg);
		modelMap.put("success", false);

		return modelMap;
	}

	@Autowired
	public void setContactService(AccountService accountService) {
		this.accountService = accountService;
	}

}
